package top.forgirl.common;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneOffset;


/**
 * 自定义时间类型的处理器
 */
public class TimeTypeHandler extends BaseTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        LocalDateTime localDateTime = (LocalDateTime) parameter;
        long timestamp = localDateTime.toEpochSecond(ZoneOffset.of("+8"));
        ps.setTimestamp(i, new Timestamp(timestamp));
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getLocalDateTimeReferSystemFromTimestamp(rs.getTimestamp(columnName));
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getLocalDateTimeReferSystemFromTimestamp(rs.getTimestamp(columnIndex));
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getLocalDateTimeReferSystemFromTimestamp(cs.getTimestamp(columnIndex));
    }

    private LocalDateTime getLocalDateTimeReferSystemFromTimestamp(Timestamp timestamp) {
        return timestamp.toLocalDateTime();
    }
}
